package com.jxust.vhremployee9092.security.handler;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.jxust.debate.feign.RedisService;
import com.jxust.debate.util.ResultEnum;
import com.jxust.debate.util.ResultVO;
import com.jxust.vhremployee9092.security.config.SelfUserDetails;
import com.jxust.vhremployee9092.security.util.JavaWebToken;
import com.jxust.vhremployee9092.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 成功登入时返回的逻辑
 * @author tyeerth
 * @date 2020/12/18 - 15:29
 */

@Component
@Slf4j
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisService redisService;

    /**
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        log.info("authentication里面的信息为{}",authentication.getPrincipal());
//        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();
        String jwttoken = (String)authentication.getPrincipal();
//        String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername(), 1500,"_secret");
//        String jwtToken = JwtTokenUtil.generateToken(jwttoken, 1500,"_secret");
        Map<String,Object> m = new HashMap<String,Object>();
        String now = DateUtil.now();
        m.put("userId",jwttoken);
        m.put("time",now);
        String token = JavaWebToken.createJavaWebToken(m);
        log.info("通过AjaxAuthenticationSuccessHandler用户登入成功请求"+token+"-------");
        //把token放入到reids中,30天自动删除
        redisService.setRedisKeyValueRemoteWithTimeout(jwttoken,token,30, TimeUnit.DAYS);
        httpServletResponse.getWriter().write(JSON.toJSONString(ResultVO.result(ResultEnum.USER_LOGIN_SUCCESS,token,true)));
    }
}